var static = require('node-static');
var http = require('http');
// Create a node-static server instance
var file = new(static.Server)();

var clinetCount = 0;
var connList =[];

// We use the http module�s createServer function and
// rely on our instance of node-static to serve the files
var app = http.createServer(function (req, res) {
  file.serve(req, res);
}).listen(8181,'192.168.129.8');

// Use socket.io JavaScript library for real-time web applications
var io = require('socket.io').listen(app);

// Let's start managing connections...
io.sockets.on('connection', function (socket){
        console.log('new connection, socket:', socket.id);

    	// Handle 'message' messages
        socket.on('message', function (message, room) {
                console.log('S --> got message: ', message +' room:'+room);
                // channel-only broadcast...
                socket.broadcast.to(room).emit('message', message);

                if(message.type === 'offer')
                {//SDP
                    console.log('SDP:\n' + message.sdp);
                }


                if(message === 'bye')
                {
                  console.log('sockets id:'+socket.id+' disconnect');
                  var index = connList.indexOf(socket.id)
                  if( index != -1)
                  {
                    connList.splice(index,1);
                  }
                  console.log('connection list len: '+connList.length+' [ '+connList+' ]');
                }
        });

        // Handle 'create or join' messages
        socket.on('create or join', function (room) {

                var numClients = connList.length;//io.sockets.clients(room).length;
                log('S --> Room ' + room + ' has ' + numClients + ' client(s)');
                log('S --> Request to create or join room', room);

                connList.push(socket.id);
                console.log('connection list len: '+connList.length+' [ '+connList+' ]');

                // First client joining...
                if (numClients == 0){
                        socket.join(room);
                        socket.emit('created', room);
                } else if (numClients == 1) {
                // Second client joining...
                        io.sockets.in(room).emit('join', room);
                        socket.join(room);
                        socket.emit('joined', room);
                } else { // max two clients
                        socket.emit('full', room);
                }
        });

        function log(){
            var array = [">>> "];
            for (var i = 0; i < arguments.length; i++) {
            	array.push(arguments[i]);
            }
            socket.emit('log', array);
            console.log('[send log]: '+array);
        }
});
